package com.yu.yupicture.manger.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.yu.yupicture.config.cosConfig;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.field.FieldUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Component
public class CosUntil {

    @Resource
    private COSClient cosClient;
    @Resource
    private cosConfig cosConfig;

    // 将文件上传到 COS
    public PutObjectResult putObject(String key, File file)
            throws CosClientException, CosServiceException {
        return cosClient.putObject(new PutObjectRequest(cosConfig.getBucket(), key, file));
    }

    // 从 COS 下载文件
    public COSObject getObject(String key)
            throws CosClientException, CosServiceException {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }


    /**
     * 上传对象（附带图片信息）
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucket(), key,
                file);
        // 对图片进行处理（获取基本信息也被视作为一种处理）
        PicOperations picOperations = new PicOperations();
        // 1 表示返回原图信息
        picOperations.setIsPicInfo(1);

        String s = FileUtil.mainName(file) + ".webp";
        // 添加图片处理规则
        List<PicOperations.Rule> ruleList = new LinkedList<>();
        PicOperations.Rule rule1 = new PicOperations.Rule();
        rule1.setBucket(cosConfig.getBucket());
        rule1.setFileId(s);
        rule1.setRule("imageMogr2/format/webp");

        //缩略图处理

            log.info("图片大于1M,生成缩略图");
            PicOperations.Rule rule2 = new PicOperations.Rule();
            rule2.setBucket(cosConfig.getBucket());
            rule2.setFileId(FileUtil.mainName( file)+"thumbnail."+(FileUtil.getSuffix(key)==null?".jpg":FileUtil.getSuffix(file)));
            rule2.setRule(String.format("imageMogr2/thumbnail/%sx%s>",128,128));
            ruleList.add(rule2);


        ruleList.add(rule1);
        // 构造处理参数
        putObjectRequest.setPicOperations(picOperations);
        picOperations.setRules(ruleList);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传图片，返回图片url
     * @param key
     * @param file
     * @return
     */
    public String userUpdateAva(String key, MultipartFile file){
        //校验参数
        check( file);
        File f=null;

        try {
            f=File.createTempFile(key,null);
            file.transferTo(f);

            //获取文件后缀名，拼装url
            String suffix = FileUtil.getSuffix(file.getOriginalFilename());
            String path = key+"." + suffix;
            this.putObject(key,f);
            return cosConfig.getHost() + key;
        } catch (IOException e) {

           throw new biusnessException(ErrorCode.PARAMS_ERROR,"文件上传失败");
        }finally {
            if (f != null) {
                boolean delete = f.delete();
                if (!delete) {
                    log.error("file delete error");
                }
            }
        }


    }
    public void check( MultipartFile file){
       if (file.isEmpty()){
           throw new biusnessException(ErrorCode.PARAMS_ERROR,"文件不能为空");
       }
       if (file.getSize() > 2 * 1024 * 1024) {
           throw new biusnessException(ErrorCode.PARAMS_ERROR, "图片大小不能超过 2MB");
       }

    }

}
